package cn.stylefeng.guns.sys.modular.system.controller;

import cn.stylefeng.guns.base.auth.context.LoginContextHolder;
import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.sys.core.util.DateUtil;
import cn.stylefeng.guns.sys.core.util.SignEncryptDncryptSignChk;
import cn.stylefeng.guns.sys.core.util.SoapUtil;
import cn.stylefeng.guns.sys.core.util.UUIDUtils;
import cn.stylefeng.guns.sys.modular.system.ApiEntity.*;
import cn.stylefeng.guns.sys.modular.system.entity.*;
import cn.stylefeng.guns.sys.modular.system.model.weixin.TemplateData;
import cn.stylefeng.guns.sys.modular.system.model.weixin.WechatTemplate;
import cn.stylefeng.guns.sys.modular.system.service.*;
import cn.stylefeng.guns.sys.modular.system.warpper.NoticeWrapper;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.apache.commons.text.StringEscapeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.HtmlUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import static cn.stylefeng.guns.sys.core.util.SignEncryptDncryptSignChk.*;

@Controller
@RequestMapping("/weiXinApi")
public class APIController {
    private Logger logger = LoggerFactory.getLogger(APIController.class);

    private String PREFIX = "/modular/system/";

    @Autowired
    private BtyBanksService btyBankService;
    @Resource
    private DictService dictService;
    @Autowired
    private BtyBorrowerService btyBorrowerService;
    @Autowired
    private MeiTuanService meiTuanService;
    @Resource
    private BtyEkbService ekbService;
    @Resource
    private BtyBxdaService btyBxdaService;
    @Resource
    private NoticeService noticeService;
    @Resource
    private BtyHhService hhService;

    /**
     * 跳转到api
     */
    @RequestMapping()
    public String noticeUpdate(ModelMap model) {
        Dict dict = dictService.getOne(new QueryWrapper<Dict>().eq("code", "access_token"));
        String accessToken = "";
        if (ToolUtil.isNotEmpty(dict)) {
            accessToken = dict.getName();
        }
        //String openid = "oaLVF5ktggE4Dy0Q9eD_-xIQpjRk";
        //String openid = "oM18PwW_aRtOaOH0F-YwsmMxT2sM";
        //String openid = "oM18PwQBM_f-4xlF7DKwnLQZ7XXc";
        //String openid = "oM18PwZuWBwyz9UEaZgxJa-sxi9w";
        String openid = "oM18PwWQsdIP3QEKcWejL1tF3X8s";
        // 发送模板消息
        //String resultUrl2 = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken;
        // 封装基础数据
        WechatTemplate wechatTemplate = new WechatTemplate();
        wechatTemplate.setTemplate_id("AC2qeKbnrgkutEWWh8nb9C73v8uA1dVa5Np8ckE5PzA");
        wechatTemplate.setTouser(openid);
        Map<String, TemplateData> mapdata = new HashMap<>();
        // 封装模板数据
        TemplateData first = new TemplateData();
        first.setValue("抱歉，您的订单无法为您配送");
        first.setColor("#173177");
        mapdata.put("first", first);

        TemplateData keyword1 = new TemplateData();
        keyword1.setValue("2020-08-28 16:01:56");//user.getMobile()
        first.setColor("#173177");
        mapdata.put("keyword1", keyword1);

        TemplateData keyword2 = new TemplateData();
        keyword2.setValue("23元");
        first.setColor("#173177");
        mapdata.put("keyword2", keyword2);

        TemplateData keyword4 = new TemplateData();
        keyword4.setValue("红咖喱牛肉 x 1份");
        first.setColor("#173177");
        mapdata.put("keyword3", keyword4);

        TemplateData keyword5 = new TemplateData();
        keyword5.setValue("已取消");
        first.setColor("#173177");
        mapdata.put("keyword4", keyword5);

        TemplateData keyword6 = new TemplateData();
        keyword6.setValue("菜品已卖光");
        first.setColor("#173177");
        mapdata.put("keyword5", keyword6);


        TemplateData keyword3 = new TemplateData();
        keyword3.setValue("请您预订其他菜品或联系客服>>");
        keyword3.setColor("#173177");
        mapdata.put("remark", keyword3);
        wechatTemplate.setData(mapdata);
        //RestTemplate restTemplate = new RestTemplate();
        String userMsg = "https://api.weixin.qq.com/cgi-bin/user/info?openid=" + openid + "&lang=zh_CN&access_token=" + accessToken;
        String userForm = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=" + accessToken;
        String formWorkMsg = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken;
        RestTemplate restTemplate = new RestTemplate();
        String userMsgS = restTemplate.getForObject(userMsg, String.class);
        String userFormS = restTemplate.getForObject(userForm, String.class);
        JSONObject weiMsg = (JSONObject) JSONObject.toJSON(wechatTemplate);
        ResponseEntity<WechatTemplate> formWorkMsgS = restTemplate.postForEntity(formWorkMsg, weiMsg, WechatTemplate.class);
        /*String responseBody = "";
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/xml; charset=utf-8"), xml);
        Request request = new sun.misc.Request.Builder()
                .url(formWorkMsg)
                .post(requestBody)
                .build();
        Response response = null;
        try {
            response = okHttpClient.newCall(request).execute();
            int status = response.code();
            if (response.isSuccessful()) {
                return response.body().string();
            }
        } catch (Exception e) {
            logger.error("okhttp3 post error >> ex = {}", ExceptionUtils.getStackTrace(e));
        } finally {
            if (response != null) {
                response.close();
            }
        }*/
        JSONObject msgJson = JSONObject.parseObject(userMsgS);
        JSONObject formJson = JSONObject.parseObject(userFormS);
        /*JSONObject json = JSONObject.toJSON(mapdata);
        JSONObject formWorkJson = JSONObject.parseObject(formWorkMsgS);
        System.out.println(json + "~~~~~~~~~");
        JSONObject result = WeixinUtil.doPostStr(url, json.toString());
        JSONObject json_arr = JSONObject.fromObject(result);
        HttpClientBuilder builder = HttpClientBuilder.create();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(new StringEntity(outstr, "utf-8"));
        try {
            HttpResponse response = builder.build().execute(httpPost);
            HttpEntity entity = response.getEntity();
            jsonObject = JSONObject.fromObject(EntityUtils.toString(entity, "utf-8"));
        }*/
        model.put("msgJson", msgJson);
        model.put("formJson", formJson);
        model.put("token", accessToken);
        model.put("wechatTemplate", wechatTemplate);
        model.put("weiMsg", weiMsg);
        model.put("formWorkMsgS", formWorkMsgS);
        return PREFIX + "token.html";
    }

    /*private String post(String url, String json, String contentType) {
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        //HttpClient
        CloseableHttpClient client = httpClientBuilder.build();
        client = (CloseableHttpClient) wrapClient(client);
        HttpPost post = new HttpPost(url);
        try {
            StringEntity s = new StringEntity(json, "utf-8");
            if (StringUtils.isBlank(contentType)) {
                s.setContentType("application/json");
            }
            s.setContentType(contentType);
            post.setEntity(s);
            HttpResponse res = client.execute(post);
            HttpEntity entity = res.getEntity();
            String str = EntityUtils.toString(entity, "utf-8");
            return str;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }*/

    /**
     * 插入数据
     */
    @RequestMapping(value = "/insert")
    @ResponseBody
    public void insert() {
        btyBankService.insert();
    }

    /**
     * 微信还款提醒
     */
    @PostMapping("repayment")
    public String repayment(ModelMap model) {
        //获取accessToken
        Dict dict = dictService.getOne(new QueryWrapper<Dict>().eq("code", "access_token"));
        String accessToken = "";
        if (ToolUtil.isNotEmpty(dict)) {
            accessToken = dict.getName();
        }

        String hkje = "";
        String lx = "";
        String name = "";
        String wxOpenId = "";

        //获取还款信息
        List<BtyBorrower> list = btyBorrowerService.borrowerList();
        for (BtyBorrower btyBorrower : list) {

            hkje = btyBorrower.getHkje();//还款本金
            lx = btyBorrower.getLx();//还款利息
            name = btyBorrower.getName();//还款人姓名
            wxOpenId = btyBorrower.getOpenid();//微信openID
            //System.out.println(hkje+"=="+lx +"--"+ name + "]]" + wxOpenId);
        }


//        String hkje = String.valueOf(list.get(1));//还款本金
//        String lx = String.valueOf(list.get(2));//还款利息
//        String name = String.valueOf(list.get(3));//还款人姓名
//        String wxOpenId = String.valueOf(list.get(4));//微信openID
//        System.out.println(hkje + "--" + lx + "++" + name + "=="  + wxOpenId);
        System.out.println(list);
        //System.out.println(hkje+"=="+lx +"--"+ name + "]]" + wxOpenId);


        //微信openID
        String openid = "oM18PwWQsdIP3QEKcWejL1tF3X8s";

        // 封装基础数据
        WechatTemplate wechatTemplate = new WechatTemplate();
        //模板ID
        wechatTemplate.setTemplate_id("a7pYJwow9WwCbS7sah2fZqFG9L52NpdQKvPoNCzMZBk");
        //接收者openid
        wechatTemplate.setTouser(openid);

        Map<String, TemplateData> mapdata = new HashMap<>();
        // 封装模板数据
        TemplateData first = new TemplateData();
        first.setValue("尊敬的xxx,您的账单如下:");
        first.setColor("#173177");
        mapdata.put("first", first);

        TemplateData keyword1 = new TemplateData();
        keyword1.setValue("2020-09-02 16:01:56");//user.getMobile()
        first.setColor("#173177");
        mapdata.put("keyword1", keyword1);

        TemplateData keyword2 = new TemplateData();
        keyword2.setValue("2020-08-01--2020-08-31");
        first.setColor("#173177");
        mapdata.put("keyword2", keyword2);

        TemplateData keyword4 = new TemplateData();
        keyword4.setValue("1000");
        first.setColor("#173177");
        mapdata.put("keyword3", keyword4);

//        TemplateData keyword5= new TemplateData();
//        keyword5.setValue("已取消");
//        first.setColor("#173177");
//        mapdata.put("keyword4", keyword5);

//        TemplateData keyword6= new TemplateData();
//        keyword6.setValue("菜品已卖光");
//        first.setColor("#173177");
//        mapdata.put("keyword5", keyword6);


        TemplateData keyword3 = new TemplateData();
        keyword3.setValue("请您及时还款.");
        keyword3.setColor("#173177");
        mapdata.put("remark", keyword3);
        wechatTemplate.setData(mapdata);
        //RestTemplate restTemplate = new RestTemplate();

        //获取用户基本信息
        String userMsg = "https://api.weixin.qq.com/cgi-bin/user/info?openid=" + openid + "&lang=zh_CN&access_token=" + accessToken;
        //获取用户列表
        String userForm = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=" + accessToken;
        //发送模板消息
        String formWorkMsg = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken;

        RestTemplate restTemplate = new RestTemplate();
        //获取用户基本信息
        String userMsgS = restTemplate.getForObject(userMsg, String.class);
        //获取用户列表
        String userFormS = restTemplate.getForObject(userForm, String.class);
        //发送模板消息
        JSONObject weiMsg = (JSONObject) JSONObject.toJSON(wechatTemplate);
        ResponseEntity<WechatTemplate> formWorkMsgS = restTemplate.postForEntity(formWorkMsg, weiMsg, WechatTemplate.class);

        //将用户基本信息转化为相应的JSONObject对象
        JSONObject msgJson = JSONObject.parseObject(userMsgS);
        //用户列表
        JSONObject formJson = JSONObject.parseObject(userFormS);


//        List<BtyBorrower> array = new ArrayList();
//        BtyBorrower btyBorrower = new BtyBorrower();
//        btyBorrower.setHkje("1010");
//        btyBorrower.setLx("1");
//        btyBorrower.setName("杨晓晨");
//        btyBorrower.setOpenid("oM18PwWQsdIP3QEKcWejL1tF3X8s");
//
//        BtyBorrower btyBorrowe = new BtyBorrower();
//        btyBorrowe.setHkje("1010");
//        btyBorrowe.setLx("1");
//        btyBorrowe.setName("陈书惠");
//        btyBorrowe.setOpenid("oM18PwQBM_f-4xlF7DKwnLQZ7XXc");
//
//        array.add(btyBorrower);
//        array.add(btyBorrowe);
//        array.add(btyBorrower);
//        System.out.println(array);
//
//        JSONObject msgJson = null ;
//        JSONObject formJson = null;
//        JSONObject weiMsg = null;
//        // 封装基础数据
//        WechatTemplate wechatTemplate = new WechatTemplate();
//        ResponseEntity<WechatTemplate> formWorkMsgS = null;
//
//        for (BtyBorrower btyBorrower1 : array) {
//
//            hkje = btyBorrower1.getHkje();//还款本金
//            lx = btyBorrower1.getLx();//还款利息
//            name = btyBorrower1.getName();//还款人姓名
//            wxOpenId = btyBorrower1.getOpenid();//微信openID
//
//
//            //模板ID
//            wechatTemplate.setTemplate_id("a7pYJwow9WwCbS7sah2fZqFG9L52NpdQKvPoNCzMZBk");
//            //接收者openid
//            wechatTemplate.setTouser(wxOpenId);
//
//            Map<String, TemplateData> mapdata = new HashMap<>();
//            // 封装模板数据
//            TemplateData first = new TemplateData();
//            first.setValue("尊敬的" + name + ",您的账单如下:");
//            first.setColor("#173177");
//            mapdata.put("first", first);
//
//            TemplateData keyword1 = new TemplateData();
//            keyword1.setValue("2020-09-02 16:01:56");//user.getMobile()
//            first.setColor("#173177");
//            mapdata.put("keyword1", keyword1);
//
//            TemplateData keyword2 = new TemplateData();
//            keyword2.setValue("2020-08-01--2020-08-31");
//            first.setColor("#173177");
//            mapdata.put("keyword2", keyword2);
//
//            TemplateData keyword4 = new TemplateData();
//            keyword4.setValue(hkje);
//            first.setColor("#173177");
//            mapdata.put("keyword3", keyword4);
//
////        TemplateData keyword5= new TemplateData();
////        keyword5.setValue("已取消");
////        first.setColor("#173177");
////        mapdata.put("keyword4", keyword5);
//
////        TemplateData keyword6= new TemplateData();
////        keyword6.setValue("菜品已卖光");
////        first.setColor("#173177");
////        mapdata.put("keyword5", keyword6);
//
//
//            TemplateData keyword3 = new TemplateData();
//            keyword3.setValue("请您及时还款.");
//            keyword3.setColor("#173177");
//            mapdata.put("remark", keyword3);
//            wechatTemplate.setData(mapdata);
//            //RestTemplate restTemplate = new RestTemplate();
//
//            //获取用户基本信息
//            String userMsg = "https://api.weixin.qq.com/cgi-bin/user/info?openid=" + wxOpenId + "&lang=zh_CN&access_token=" + accessToken;
//            //获取用户列表
//            String userForm = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=" + accessToken;
//            //发送模板消息
//            String formWorkMsg = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken;
//
//            RestTemplate restTemplate = new RestTemplate();
//            //获取用户基本信息
//            String userMsgS = restTemplate.getForObject(userMsg, String.class);
//            //获取用户列表
//            String userFormS = restTemplate.getForObject(userForm, String.class);
//            //发送模板消息
//             weiMsg = (JSONObject) JSONObject.toJSON(wechatTemplate);
//             formWorkMsgS = restTemplate.postForEntity(formWorkMsg, weiMsg, WechatTemplate.class);
//
//            //将用户基本信息转化为相应的JSONObject对象
//             msgJson = JSONObject.parseObject(userMsgS);
//            //用户列表
//             formJson = JSONObject.parseObject(userFormS);
//
//        }
//
//


        model.put("msgJson", msgJson);
        model.put("formJson", formJson);
        model.put("token", accessToken);
        model.put("wechatTemplate", wechatTemplate);
        model.put("weiMsg", weiMsg);
        model.put("formWorkMsgS", formWorkMsgS);
        return PREFIX + "token.html";
    }

    /**
     * webservice页面
     */
    @GetMapping("webservice")
    public String webservice() {
        return PREFIX + "webservice.html";
    }

    /**
     * webservices数据
     */
    @ResponseBody
    @PostMapping("webserviceIn")
    public String webserviceIn(String money) {
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd HHmmss");//设置日期格式
        String number = df.format(new Date());
        String[] format = df.format(new Date()).split(" ");
        String date = format[0];
        String time = format[1];
        StringBuilder soap = new StringBuilder(); //构造请求报文
        //soap.append(" <?xml version='1.0' encoding='utf-8'?>");
        soap.append(" <soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>");
        //<--Header标头信息start-->
        soap.append(" <soap:Body>");
        soap.append(" <postesalescreate xmlns='http://tempurl.org'>");
        soap.append(" <astr_request>");
        soap.append(" <header>");
        soap.append(" <licensekey></licensekey>");
        //用户名
        soap.append(" <username>SJZMIXC</username>");
        //密码
        soap.append(" <password>SJZmixc@01</password>");
        soap.append(" <lang></lang>");
        soap.append(" <pagerecords>1</pagerecords>");
        soap.append(" <pageno>1</pageno>");
        soap.append(" <updatecount>1</updatecount>");
        //消息类型
        soap.append(" <messagetype>SALESDATA</messagetype>");
        //消息id
        soap.append(" <messageid>332</messageid>");
        //版本编号
        soap.append(" <version>V332M</version>");
        soap.append(" </header>");
        //<--Header标头信息end-->

        //<--SalesTotal:销售单主表start-->
        soap.append("  <esalestotal>");
        //交易日期
        soap.append(" <txdate_yyyymmdd>" + date + "</txdate_yyyymmdd>");
        //交易时间
        soap.append(" <txtime_hhmmss>" + time + "</txtime_hhmmss>");
        //商城编号
        soap.append(" <mallid>HB</mallid>");
        //店铺号
        soap.append(" <storecode>BLGZ031N01</storecode>");
        //收银机号
        soap.append(" <tillid>01</tillid>");
        //销售单号
        soap.append(" <txdocno>" + number + "</txdocno>");
        //收银员编号
        soap.append(" <cashier>01</cashier>");
        //VIP号
        soap.append(" <vipcode></vipcode>");
        //销售员
        soap.append(" <salesman></salesman>");
        //数量
        soap.append(" <netqty>1</netqty>");
        //销售净金额
        soap.append(" <netamount>" + money + "</netamount>");
        //预留字段
        soap.append(" <extendparam></extendparam>");
        soap.append(" </esalestotal>");
        //<--SalesTotal:销售单主表end-->

        //<--SalesI销售单货品明细表start-->
        soap.append(" <esalesitems>");
        soap.append(" <esalesitem>");
        //商品行号
        soap.append(" <lineno>2</lineno>");
        //商品编号
        soap.append(" <itemcode>BLGZ031N0101</itemcode>");
        //数量
        soap.append(" <qty>1</qty>");
        //折扣金额
        soap.append(" <discountamount>0</discountamount>");
        //净金额
        soap.append(" <netamount>" + money + "</netamount>");
        //获得的积分
        soap.append(" <bonusearn>0</bonusearn>");
        //预留字段
        soap.append(" <extendparam></extendparam>");
        //货品备注
        soap.append(" <salesitemremark></salesitemremark>");
        soap.append(" </esalesitem>");
        soap.append(" </esalesitems>");
        //<--SalesI销售单货品明细表end-->

        //<!--销售单付款明细表start-->
        soap.append(" <esalestenders>");
        soap.append(" <esalestender>");
        //行号
        soap.append(" <lineno>2</lineno>");
        //付款代码
        soap.append(" <tendercode>CH</tendercode>");
        //付款金额
        soap.append(" <payamount>" + money + "</payamount>");
        //本位币金额
        soap.append(" <baseamount>" + money + "</baseamount>");
        //找零金额
        soap.append(" <excessamount>0</excessamount>");
        //预留字段
        soap.append(" <extendparam></extendparam>");
        //备注信息
        soap.append(" <remark></remark>");
        soap.append(" </esalestender>");
        soap.append(" </esalestenders>");
        //<!--SalesTender销售单付款明细表end-->

        soap.append(" </astr_request>");
        soap.append(" </postesalescreate>");
        soap.append(" </soap:Body>");
        soap.append(" </soap:Envelope>");
        String requestSoap = soap.toString();
        String serviceAddress = "http://124.239.142.218:60001/eSales/esales.asmx?WSDL";//服务地址(将url替换成自己项目的地址)
        String charSet = "utf-8";
        String contentType = "text/xml; charset=utf-8";
        //String contentType="application/soap+xml; charset=utf-8";
        //第一步：调用方法getResponseSoap。返回响应报文和状态码
        Map<String, Object> responseSoapMap = SoapUtil.responseSoap(requestSoap, serviceAddress, charSet, contentType);
        Integer statusCode = (Integer) responseSoapMap.get("statusCode");
        String result = "";
      /*  if (statusCode == 200) {
            String responseSoap = (String) responseSoapMap.get("responseSoap");
            System.out.println("返回的报文为----" + responseSoap);
            // String targetNodeName="ESB_RETURN_CODE";
            String targetNodeName = "responsecode";
            //第二步：调用strXmlToDocument方法。将字符串类型的XML的响应报文 转化成Document结构文档
            Document doc = Jdom2XMLUtil.strXmlToDocument(responseSoap);
            //第三步：调用getValueByElementName方法。递归获得目标节点的值
            result = Jdom2XMLUtil.getValueByElementName(doc, targetNodeName);
            System.out.println(result);
            if (!StringUtils.isEmpty(result)) {
                System.out.println(result);
            } else {
                result = "添加失败";
            }
        } else {
            result = "请求失败!";
        }*/
        return result;
    }

    /**
     * 美团登入判断
     */
    @GetMapping("meiTuanSign")
    public String meiTuanSign() {
        return PREFIX + "meiTuan/meiTuanSign.html";
    }

    /**
     * 美团登入页面
     */
    @ResponseBody
    @PostMapping("judge")
    public String judge(String yaoMa) {
        String judge = meiTuanService.judge(yaoMa);
        if (judge != null && !"".equals(judge)) {
            return judge;
        }
        return "0";
    }

    /**
     * 美团录入页面
     */
    @GetMapping("meiTuanMsg")
    public String meiTuanMsg(String yaoMa, ModelMap map) {
        map.put("yaoMa", yaoMa);
        return PREFIX + "meiTuan/meiTuanMsg.html";
    }

    /**
     * 美团详情页面
     */
    @GetMapping("meiTuan")
    public String meiTuan(ModelMap map) {
        return PREFIX + "meiTuan/meiTuan.html";
    }

    /**
     * 美团录入信息
     */
    @ResponseBody
    @PostMapping("insertMeiTuan")
    public Integer insertMeiTuan(MeiTuan meiTuan) {
        return meiTuanService.insertMeiTuan(meiTuan);
    }

    /**
     * 美团登入判断
     */
    @RequestMapping("meiTuanList")
    public String meiTuanList() {
        return PREFIX + "meiTuan/meiTuanList.html";
    }

    /**
     * 获取美团列表
     */
    @RequestMapping(value = "listMt")
    @ResponseBody
    public Object list(String dm, String sjh, String ym, String timeLimit, String xf, String sex, String xm) {
        //拼接查询条件
        String beginTime = "";
        String endTime = "";
        if (ToolUtil.isNotEmpty(timeLimit)) {
            String[] split = timeLimit.split(" - ");
            beginTime = split[0];
            endTime = split[1] + " 23:59:59";
        }
        String username = LoginContextHolder.getContext().getUser().getAccount();
        Page<Map<String, Object>> list = null;
        if (!username.equals("admin")) {
            list = meiTuanService.list(dm, sjh, username, beginTime, endTime, xf, sex, xm);
        } else {
            list = meiTuanService.list(dm, sjh, ym, beginTime, endTime, xf, sex, xm);
        }
        Page<Map<String, Object>> wrap = new NoticeWrapper(list).wrap();
        return LayuiPageFactory.createPageInfo(wrap);
    }

    /**
     * 获取美团列表
     */
    @RequestMapping(value = "listExport")
    @ResponseBody
    public Object listExport(String dm, String sjh, String ym, String timeLimit, String xf, String sex) {
        //拼接查询条件
        String beginTime = "";
        String endTime = "";
        if (ToolUtil.isNotEmpty(timeLimit)) {
            String[] split = timeLimit.split(" - ");
            beginTime = split[0];
            endTime = split[1] + " 23:59:59";
        }
        String username = LoginContextHolder.getContext().getUser().getAccount();
        List<Map<String, Object>> list = null;
        if (!username.equals("admin")) {
            list = meiTuanService.listExport(dm, sjh, username, beginTime, endTime, xf, sex);
        } else {
            list = meiTuanService.listExport(dm, sjh, ym, beginTime, endTime, xf, sex);
        }
        return list;
    }

    @ResponseBody
    @GetMapping("/cmbc")
    public ResponseData cmbcTest() {
        try {
            RestTemplate restTemplate = new RestTemplate();
            String dates = DateUtil.getStampNow();
            String date = dates.substring(0, 8);
            String time = dates.substring(dates.length() - 6);
            String yesterdayDate = DateUtil.getYesterDay();
            //子账簿交易查询 //M23002021050001172285	20210508180504172285  9734000008777090     9734000008777108
//            String context="{\"platformId\":\"M23002021040001171743\",\"merchantNo\":\"M23002021040001171743\"," +
//                    "\"contractId\":\"20210508180504172285\",\"outOptSeq\":\"23002021040001171743b87271ea4c00498c952a87ba3bab82\",\"transDate\":\""+date+"\",\"transTime\":\""+time+"\"" +
//                    ",\"accNo\":\"9734000008775375\",\"totalNum\":\"200\",\"dcFlag\":\"2\",\"detStat\":\"00\",\"startDate\":\""+yesterdayDate+"\",\"endDate\":\""+yesterdayDate+"\"}";
            String context = "{\"platformId\":\"A00002021040001171544\",\"merchantNo\":\"M23002021050001172285\"," +
                    "\"contractId\":\"20210508180504172285\",\"outOptSeq\":\"23002021040001171743b87271ea4c00498c952a87ba3bab82\",\"transDate\":\"" + date + "\",\"transTime\":\"" + time + "\"" +
                    ",\"accNo\":\"9734000008777090\",\"totalNum\":\"200\",\"dcFlag\":\"2\",\"detStat\":\"00\",\"startDate\":\"20210510\",\"endDate\":\"20210510\"}";
            //签名
            String sign = getSign(context);
            System.out.println("--------------------------------------");
            System.out.println("签名：");
            System.out.println(sign);
            //加密前
            String signContext = SignEncryptDncryptSignChk.sign(sign, context);
            System.out.println("--------------------------------------");
            System.out.println("加密前：");
            System.out.println(signContext);
            //加密后
            String encryptContext = encrypt(signContext);
            System.out.println("--------------------------------------");
            System.out.println("加密后：");
            System.out.println(encryptContext);

            JSONObject json = new JSONObject();
            json.put("businessContext", encryptContext);
            System.out.println("json:" + json);
            HttpHeaders headers = new HttpHeaders();
            MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
            headers.setContentType(type);
            headers.add("Accept", MediaType.APPLICATION_JSON.toString());
            HttpEntity<String> formEntity = new HttpEntity<String>(json.toString(), headers);
            String url = "https://epay.cmbc.com.cn/appweb/bill/subBookTradeQry.do";
            String result = restTemplate.postForEntity(url, formEntity, String.class).getBody();
            System.out.println("result:" + result);
            JsonParser jp = new JsonParser();
            //将json字符串转化成json对象
            JsonObject jo = jp.parse(result).getAsJsonObject();
            String flag = jo.get("gateReturnType").getAsString();
            Integer currNum = 0;
            Integer totalPage = 0;

            if (flag.equals("S")) {
                String businessContext = jo.get("businessContext").getAsString();
                String dncryptContexts = dncrypt(businessContext);
                System.out.println("--------------------------------------");
                System.out.println("解密后111：");
                System.out.println(dncryptContexts);

                JsonObject jos = jp.parse(dncryptContexts).getAsJsonObject();

                String body = jos.get("body").getAsString();
                JSONObject jsonObject = JSON.parseObject(body);
                currNum = Integer.parseInt(jsonObject.getString("currNum"));
                totalPage = Integer.parseInt(jsonObject.getString("totalPage"));
                //数组对象反序列化成集合
                List<CmbcData> list = JSON.parseArray(jsonObject.getString("outList"), CmbcData.class);
                System.out.println("currNum:" + currNum);
                System.out.println("listsize:" + list.size());
                System.out.println(list.get(0).getPayeeAccNo() + "======" + list.get(0).getTranAmount());
                return ResponseData.success(list);
//                while(currNum<totalPage) {
//                    currNum++;
//                    cmbc(currNum);
//                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public ResponseData cmbc(Integer currNum) {
        try {
            RestTemplate restTemplate = new RestTemplate();
            String dates = DateUtil.getStampNow();
            String date = dates.substring(0, 8);
            String time = dates.substring(dates.length() - 6);
            String yesterdayDate = DateUtil.getYesterDay();
            //子账簿交易查询 //M23002021050001172285	20210508180504172285
//            String context="{\"platformId\":\"M23002021040001171743\",\"merchantNo\":\"M23002021040001171743\"," +
//                    "\"contractId\":\"20210425185836171743\",\"outOptSeq\":\"23002021040001171743b87271ea4c00498c952a87ba3bab82\",\"transDate\":\""+date+"\",\"transTime\":\""+time+"\"" +
//                    ",\"accNo\":\"9734000008775375\",\"totalNum\":\"200\",\"dcFlag\":\"2\",\"detStat\":\"00\",\"startDate\":\""+yesterdayDate+"\",\"endDate\":\""+yesterdayDate+"\"}";
            String context = "{\"platformId\":\"M23002021040001171743\",\"merchantNo\":\"M23002021040001171743\"," +
                    "\"contractId\":\"20210425185836171743\",\"outOptSeq\":\"23002021040001171743b87271ea4c00498c952a87ba3bab82\",\"transDate\":\"" + date + "\",\"transTime\":\"" + time + "\"" +
                    ",\"accNo\":\"9734000008775375\",\"startNum\":\"" + currNum + "\",\"totalNum\":\"100\",\"dcFlag\":\"2\",\"detStat\":\"00\",\"startDate\":\"20210504\",\"endDate\":\"20210504\"}";
            //签名
            String sign = getSign(context);
            System.out.println("--------------------------------------");
            System.out.println("签名：");
            System.out.println(sign);
            //加密前
            String signContext = SignEncryptDncryptSignChk.sign(sign, context);
            System.out.println("--------------------------------------");
            System.out.println("加密前：");
            System.out.println(signContext);
            //加密后
            String encryptContext = encrypt(signContext);
            System.out.println("--------------------------------------");
            System.out.println("加密后：");
            System.out.println(encryptContext);

            JSONObject json = new JSONObject();
            json.put("businessContext", encryptContext);
            System.out.println("json:" + json);
            HttpHeaders headers = new HttpHeaders();
            MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
            headers.setContentType(type);
            headers.add("Accept", MediaType.APPLICATION_JSON.toString());
            HttpEntity<String> formEntity = new HttpEntity<String>(json.toString(), headers);
            String url = "https://epay.cmbc.com.cn/appweb/bill/subBookTradeQry.do";
            String result = restTemplate.postForEntity(url, formEntity, String.class).getBody();
            System.out.println("result:" + result);
            JsonParser jp = new JsonParser();
            //将json字符串转化成json对象
            JsonObject jo = jp.parse(result).getAsJsonObject();
            String flag = jo.get("gateReturnType").getAsString();
            //Integer totalCount =jo.get("totalCount").getAsInt();
            // Integer currNum =Integer.parseInt(jo.get("currNum").getAsString());
            // Integer totalPage =Integer.parseInt(jo.get("totalPage").getAsString());

            if (flag.equals("S")) {
                String businessContext = jo.get("businessContext").getAsString();
                String dncryptContexts = dncrypt(businessContext);
                System.out.println("--------------------------------------");
                System.out.println("解密后111：");
                System.out.println(dncryptContexts);

                JsonObject jos = jp.parse(dncryptContexts).getAsJsonObject();
                String body = jos.get("body").getAsString();
                JSONObject jsonObject = JSON.parseObject(body);
                //数组对象反序列化成集合
                List<CmbcData> list = JSON.parseArray(jsonObject.getString("outList"), CmbcData.class);
                System.out.println("listsize:" + list.size());
                System.out.println("currNum:" + currNum);
                System.out.println(list.get(0).getPayeeAccNo() + "======" + list.get(0).getTranAmount());
                return ResponseData.success(list);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @ResponseBody
    @GetMapping("/ye")
    public ResponseData ye() {
        try {
            RestTemplate restTemplate = new RestTemplate();
            String dates = DateUtil.getStampNow();
            String date = dates.substring(0, 8);
            String time = dates.substring(dates.length() - 6);
            String yesterdayDate = DateUtil.getYesterDay();
            //子账簿余额查询
//            String context="{\"platformId\":\"M23002021040001171743\",\"merchantNo\":\"M23002021040001171743\"," +
//                    "\"contractId\":\"20210425185836171743\",\"outOptSeq\":\"23002021040001171743b87271ea4c00498c952a87ba3bab82\",\"transDate\":\""+date+"\",\"transTime\":\""+time+"\"" +
//                    ",\"accNo\":\"9734000008775375\",\"totalNum\":\"200\",\"dcFlag\":\"2\",\"detStat\":\"00\",\"startDate\":\""+yesterdayDate+"\",\"endDate\":\""+yesterdayDate+"\"}";
//            String context="{\"platformId\":\"M23002021040001171743\",\"merchantNo\":\"M23002021040001171743\"," +
//                    "\"contractId\":\"20210425185836171743\",\"outOptSeq\":\"23002021040001171743b87271ea4c00498c952a87ba3bab82\",\"transDate\":\""+date+"\",\"transTime\":\""+time+"\"" +
//                    ",\"accNo\":\"9734000008775375\",\"totalNum\":\"200\",\"dcFlag\":\"2\",\"detStat\":\"00\",\"startDate\":\"20210504\",\"endDate\":\"20210504\"}";
//            String context="{\"platformId\":\"M23002021040001171743\",\"merchantNo\":\"M23002021040001171743\"," +
//                    "\"contractId\":\"20210425185836171743\",\"outOptSeq\":\"23002021040001171743b87271ea4c00498c952a87ba3bab82\",\"transDate\":\"20210506\",\"transTime\":\"080000\",\"accNo\":\"9734000008775375\"}";
            //M23002021050001172285	20210508180504172285
            String context = "{\"platformId\":\"A00002021040001171544\",\"merchantNo\":\"M23002021050001172285\"," +
                    "\"contractId\":\"20210508180504172285\",\"outOptSeq\":\"23002021040001171743b87271ea4c00498c952a87ba3bab82\",\"AcctStat\":\"1\",\"startNum\":\"1\"}";
            //签名
            String sign = getSign(context);
            System.out.println("--------------------------------------");
            System.out.println("签名：");
            System.out.println(sign);
            //加密前
            String signContext = SignEncryptDncryptSignChk.sign(sign, context);
            System.out.println("--------------------------------------");
            System.out.println("加密前：");
            System.out.println(signContext);
            //加密后
            String encryptContext = encrypt(signContext);
            System.out.println("--------------------------------------");
            System.out.println("加密后：");
            System.out.println(encryptContext);

            JSONObject json = new JSONObject();
            json.put("businessContext", encryptContext);
            System.out.println("json:" + json);
            HttpHeaders headers = new HttpHeaders();
            MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
            headers.setContentType(type);
            headers.add("Accept", MediaType.APPLICATION_JSON.toString());
            HttpEntity<String> formEntity = new HttpEntity<String>(json.toString(), headers);
            //String url = "https://epay.cmbc.com.cn/appweb/bill/bidStdQryVacctBal.do";
            String url = "https://epay.cmbc.com.cn/appweb/bill/bidStdQryAcctList.do";
            String result = restTemplate.postForEntity(url, formEntity, String.class).getBody();
            System.out.println("result:" + result);
            JsonParser jp = new JsonParser();
            //将json字符串转化成json对象
            JsonObject jo = jp.parse(result).getAsJsonObject();
            String flag = jo.get("gateReturnType").getAsString();
            Integer currNum = 0;
            Integer totalPage = 0;

            if (flag.equals("S")) {
                String businessContext = jo.get("businessContext").getAsString();
                String dncryptContexts = dncrypt(businessContext);
                System.out.println("--------------------------------------");
                System.out.println("解密后111：");
                System.out.println(dncryptContexts);

//                JsonObject jos = jp.parse(dncryptContexts).getAsJsonObject();
//
//                String body=jos.get("body").getAsString();
//                JSONObject jsonObject = JSON.parseObject(body);
//                currNum =Integer.parseInt(jsonObject.getString("currNum"));
//                totalPage =Integer.parseInt(jsonObject.getString("totalPage"));
//                //数组对象反序列化成集合
//                List<CmbcData>   list = JSON.parseArray(jsonObject.getString("outList"), CmbcData.class);
//                System.out.println("currNum:"+currNum);
//                System.out.println("listsize:"+list.size());
//                System.out.println(list.get(0).getPayeeAccNo()+"======"+list.get(0).getTranAmount());
                return ResponseData.success(dncryptContexts);
//                while(currNum<totalPage) {
//                    currNum++;
//                    cmbc(currNum);
//                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 易快报配置出站消息接口
     * @param ekbs
     * @param response
     * @return
     */
    @ResponseBody
    @PostMapping("/ekb")
    public ResponseData ekb(@RequestBody Ekbs ekbs, HttpServletResponse response) {
        try {
            //System.out.println("ekbs:"+ekbs);
            logger.info("ekbs:"+ekbs);
            //System.out.println("111111");
            String ekbId=ekbs.getFlowId();
            BtyEkb ekb = new BtyEkb();
            ekb.setId(UUIDUtils.getId());
            ekb.setTitle(ekbs.getTitle());
            ekb.setEkbId(ekbs.getFlowId());
            ekb.setNodeId(ekbs.getNodeId());
            ekb.setBxr(ekbs.getSubmitterId().getName());
            //ekb.setFkr(StringEscapeUtils.unescapeHtml4(ekbs.getPayeeInfo().getName().replaceAll("\\s*", "")));
            ekb.setFkr(HtmlUtils.htmlUnescape(ekbs.getPayeeInfo().getName().replace(" ","")));
            ekb.setCode(ekbs.getCode());
            String bm=ekbs.getExpenseDepartment().getName();
            if(bm.equals("半天妖潍坊高密金孚隆中心店")){
              bm="潍坊高密金孚隆购物广场店";
            }
            if(bm.equals("半天妖福州万象九宜城店")){
                bm="半天妖福建福州万象九宜城店";
            }
            if(bm.equals("半天妖青岛胶州利群购物广场店")){
                bm="半天妖山东青岛胶州利群店";
            }
            if(bm.equals("上饶万达店")){
                bm="上饶信州万达店";
            }
            if(bm.equals("半天妖江苏镇江吾悦店")){
                bm="半天妖镇江吾悦店";
            }
            if(bm.equals("半天妖北京大兴宾馆店")){
                bm="半天妖北京大兴店";
            }
            if(bm.equals("新乡新玛特")){
                bm="新乡市大商新玛特店";
            }
            if(bm.equals("半天妖滕州人和店")){
                bm="半天妖滕州人和广场店";
            }
            if(bm.equals("威海荣成九龙城店")){
                bm="半天妖威海荣成市九龙城店";
            }
            if(bm.equals("杭州滨江宝龙城店")){
                bm="半天妖杭州滨江宝龙城店";
            }
            ekb.setBm(bm);
//            if(ToolUtil.isNotEmpty(ekbs.getU_tenday())){
//               ekb.setDjbz("ten");
//            }
            if(ToolUtil.isNotEmpty(ekbs.getDescription())){
                ekb.setRemark(DateUtil.splitNotNumber(ekbs.getDescription()));
            }
            ekb.setSumAmount(new BigDecimal(ekbs.getPayMoney().getAmount()));
            String yhk = ekbs.getPayeeInfo().getCardNo();
            ekb.setYhk(yhk);
            //通过银行卡号获取银行简称
            RestTemplate restTemplate = new RestTemplate();
            String url3 = "https://ccdcapi.alipay.com/validateAndCacheCardInfo.json?_input_charset=utf-8&cardNo=" + yhk + "&cardBinCheck=true";
            String content = restTemplate.getForObject(url3, String.class);
            JSONObject jsonObject = JSONObject.parseObject(content);

            String bank;
            if (ToolUtil.isNotEmpty(jsonObject.get("bank"))) {
                //银行简称
                bank = jsonObject.get("bank").toString();
                //通过银行简称获取行号
                String code = btyBxdaService.getBankCode(bank);
                ekb.setHh(code);
            }else{
                if(ToolUtil.isNotEmpty(yhk)){
                    List<BtyHh> list=hhService.list(new QueryWrapper<BtyHh>().eq("yhk",yhk));
                    if(list.size()>0){
                        ekb.setHh(list.get(0).getHh());
                    }
                }
            }
            ekb.setBank(ekbs.getPayeeInfo().getBank());
            ekb.setZhmc(ekbs.getPayeeInfo().getBranch());
            ekb.setYyr(DateUtil.getNowDate());
            ekb.setCjsj(new Date());
            //查询易快报单号是否已经存在，如果存在就更新，否则就保存数据
            BtyEkb btyEkb=ekbService.getOne(new QueryWrapper<BtyEkb>().eq("ekb_id",ekbId));
            if(ToolUtil.isNotEmpty(btyEkb)){
                btyEkb.setBm(bm);
                btyEkb.setBank(ekbs.getPayeeInfo().getBank());
                btyEkb.setZhmc(ekbs.getPayeeInfo().getBranch());
                btyEkb.setYyr(DateUtil.getNowDate());
                btyEkb.setCjsj(new Date());
                if(ToolUtil.isNotEmpty(ekbs.getDescription())){
                    btyEkb.setRemark(DateUtil.splitNotNumber(ekbs.getDescription()));
                }
                if(ToolUtil.isNotEmpty(btyEkb.getBms())){
                    btyEkb.setBms(btyEkb.getBms());
                }
                if(ToolUtil.isNotEmpty(btyEkb.getFtbl())){
                    btyEkb.setFtbl(btyEkb.getFtbl());
                }
                if(ToolUtil.isNotEmpty(btyEkb.getFtje())){
                    btyEkb.setFtje(btyEkb.getFtje());
                }
                List<BtyEkb>list8=ekbService.list(new QueryWrapper<BtyEkb>().eq("ftid",btyEkb.getId()));
                if(list8.size()<=0){
                    btyEkb.setSumAmount(new BigDecimal(ekbs.getPayMoney().getAmount()));
                }
                btyEkb.setBxr(ekbs.getSubmitterId().getName());
                //btyEkb.setFkr(StringEscapeUtils.unescapeHtml4(ekbs.getPayeeInfo().getName().replaceAll("\\s*", "")));
                btyEkb.setFkr(HtmlUtils.htmlUnescape(ekbs.getPayeeInfo().getName().replace(" ","")));
                btyEkb.setYhk(ekbs.getPayeeInfo().getCardNo());
                ekbService.updateById(btyEkb);
            }else {
                ekbService.save(ekb);
            }

            HttpHeaders headers = new HttpHeaders();
            MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
            headers.setContentType(type);
            JSONObject json = new JSONObject();
            json.put("appKey", "32de31e8-9a31-4cf9-a69b-74ddee365cf2");
            json.put("appSecurity", "149b3780-99bf-4431-976e-27d80896452f");
            headers.add("Accept", MediaType.APPLICATION_JSON.toString());
            HttpEntity<String> formEntity = new HttpEntity<String>(json.toString(), headers);
            String url = "https://dd2.ekuaibao.com/api/openapi/v1/auth/getAccessToken";
            String result = restTemplate.postForEntity(url, formEntity, String.class).getBody();
            JsonParser jp = new JsonParser();
            //将json字符串转化成json对象
            JsonObject jo = jp.parse(result).getAsJsonObject();
            //获取accessToken
            String accessToken = jo.get("value").getAsJsonObject().get("accessToken").getAsString();
            String url1 = "https://dd2.ekuaibao.com/api/openapi/v1/flowDetails?flowId="+ekbId+"&accessToken=" + accessToken;
            Bill bill = restTemplate.getForEntity(url1,Bill.class).getBody();
            //费用分摊部门
            String bms = "";
            //费用分摊比例
            String ftbl="";
            //费用分摊金额
            String ftjes="";
            //获取易快报报销单费用分摊的相关信息
            List<Bill.ValueBean.FormBean.Details> list=bill.getValue().getForm().getDetails();
            for (Bill.ValueBean.FormBean.Details details : list) {
                if(ToolUtil.isNotEmpty(details.getFeeTypeForm().getApportions())) {
                    List<Bill.ValueBean.FormBean.Details.FeeTypeFormBean.ApportionsBean> apportionsBeanList = details.getFeeTypeForm().getApportions();
                    for (Bill.ValueBean.FormBean.Details.FeeTypeFormBean.ApportionsBean apportionsBean : apportionsBeanList) {
                        String  apportionPercent=apportionsBean.getApportionForm().getApportionPercent();
                        ftbl=ftbl+apportionPercent+",";
                        String ftje=apportionsBean.getApportionForm().getApportionMoney().getStandard();
                        ftjes=ftjes+ftje+",";
                        String ftbmId=apportionsBean.getApportionForm().getExpenseDepartment();
                        //通过部门id获取部门名称
                        String url2 = "https://dd2.ekuaibao.com/api/openapi/v1/departments/$"+ftbmId+"?departmentBy=id&accessToken=" + accessToken;
                        String result2 = restTemplate.getForEntity(url2,String.class).getBody();
                        //将json字符串转化成json对象
                        JsonObject jo1 = jp.parse(result2).getAsJsonObject();
                        //获取部门名称
                        String bm1 = jo1.get("value").getAsJsonObject().get("name").getAsString();
                        if(bm1.equals("半天妖潍坊高密金孚隆中心店")){
                            bm1="潍坊高密金孚隆购物广场店";
                        }
                        if(bm1.equals("半天妖福州万象九宜城店")){
                            bm1="半天妖福建福州万象九宜城店";
                        }
                        if(bm1.equals("半天妖青岛胶州利群购物广场店")){
                            bm1="半天妖山东青岛胶州利群店";
                        }
                        if(bm1.equals("上饶万达店")){
                            bm1="上饶信州万达店";
                        }
                        if(bm1.equals("半天妖江苏镇江吾悦店")){
                            bm1="半天妖镇江吾悦店";
                        }
                        if(bm1.equals("半天妖北京大兴宾馆店")){
                            bm1="半天妖北京大兴店";
                        }
                        if(bm1.equals("新乡新玛特")){
                            bm1="新乡市大商新玛特店";
                        }
                        if(bm1.equals("半天妖滕州人和店")){
                            bm1="半天妖滕州人和广场店";
                        }
                        if(bm1.equals("威海荣成九龙城店")){
                            bm1="半天妖威海荣成市九龙城店";
                        }
                        if(bm.equals("杭州滨江宝龙城店")){
                            bm="半天妖杭州滨江宝龙城店";
                        }
                        bms=bms+bm1+",";
                        //System.out.println("分摊部门："+bm1+"分摊比例:"+apportionPercent+  "分摊金额："+ftje);
                        BtyEkb ftEkb=new BtyEkb();
                        ftEkb.setId(UUIDUtils.getId());
                        ftEkb.setTitle(ekbs.getTitle());
                        if(ToolUtil.isNotEmpty(ekbs.getDescription())){
                            ftEkb.setRemark(DateUtil.splitNotNumber(ekbs.getDescription()));
                        }
                        ftEkb.setBm(bm1);
                        ftEkb.setSumAmount(new BigDecimal(ftje));
                        //ftEkb.setEkbId(bxd.getFlowId());
                        //ftEkb.setNodeId(bxd.getNodeId());

                        BtyEkb ekb1=ekbService.getOne(new QueryWrapper<BtyEkb>().eq("ekb_id",ekbId));
                        if(ToolUtil.isNotEmpty(ekb1)){
                            ftEkb.setBxr(ekb1.getBxr());
                            ftEkb.setFkr(HtmlUtils.htmlUnescape(ekb1.getFkr().replace(" ","")));
                            ftEkb.setCode(ekb1.getCode());
                            ftEkb.setFtid(ekb1.getId());
                            ftEkb.setBank(ekb1.getBank());
                            ftEkb.setYhk(ekb1.getYhk());
                            ftEkb.setZhmc(ekb1.getZhmc());
                            ftEkb.setHh(ekb1.getHh());
                            ftEkb.setRemark(ekb1.getRemark());
                            ftEkb.setTitle(ekb1.getTitle());
                            if(ToolUtil.isNotEmpty(ekb1.getDjbz())){
                                ftEkb.setDjbz(ekb1.getDjbz());
                            }
                        }
                        ftEkb.setSumAmount(new BigDecimal(ftje));
                        ftEkb.setBm(bm1);
                        ftEkb.setYyr(DateUtil.getNowDate());
                        ftEkb.setFtbz(0);
                        ekbService.save(ftEkb);
                    }
                }
            }
            if(ftbl.length()>0){
                ftbl=ftbl.substring(0, ftbl.length()-1);
            }
            if(ftjes.length()>0){
                ftjes=ftjes.substring(0, ftjes.length()-1);
            }
            if(bms.length()>0){
                bms=bms.substring(0, bms.length()-1);
            }
            //更新费用承担部门，分摊比例，分摊费用到易快报表中
            BtyEkb ekb1 =ekbService.getOne(new QueryWrapper<BtyEkb>().eq("ekb_id",ekbId));
            List<BtyEkb>lists=new ArrayList<>();
            if(ToolUtil.isNotEmpty(ekb1)){
                lists=ekbService.list(new QueryWrapper<BtyEkb>().eq("ftid",ekb1.getId()));
            }
            if(ToolUtil.isNotEmpty(ekb1)&&lists.size()>0){
                if(ToolUtil.isNotEmpty(bms)){
                    ekb1.setBms(bms);
                }
                if(ToolUtil.isNotEmpty(ftbl)){
                    ekb1.setFtbl(ftbl);
                }
                if(ToolUtil.isNotEmpty(ftjes)){
                    ekb1.setFtje(ftjes);
                }
                ekb1.setFtbz(0);
                ekb1.setSumAmount(BigDecimal.ZERO);
                ekbService.updateById(ekb1);
            }

        } catch (Exception e) {
            logger.info("易快报异常："+e);
            e.printStackTrace();
        }
        //System.out.println("单据id:" + ekbs.getFlowId() + "流程id:" + ekbs.getNodeId());
        response.setStatus(204);
        return ResponseData.success();

    }
    /**
     * 易快报预付款报销单配置出站消息接口
     * @param bxd
     * @param response
     * @return
     */
    @ResponseBody
    @PostMapping("/ekbBxd")
    public ResponseData ekbBxd(@RequestBody Yfkbxd bxd, HttpServletResponse response) {
        try {
            System.out.println("预付款报销单或核销单：" + bxd);
            logger.info("预付款报销单或核销单:" + bxd);
            BtyEkb ekb = new BtyEkb();
            ekb.setId(UUIDUtils.getId());
            ekb.setTitle(bxd.getTitle());
            ekb.setEkbId(bxd.getFlowId());
            String ekbId = bxd.getFlowId();
            ekb.setNodeId(bxd.getNodeId());
            ekb.setBxr(bxd.getSubmitterId().getName());
            ekb.setCode(bxd.getCode());
            if (ToolUtil.isNotEmpty(bxd.getDescription())) {
                ekb.setRemark(DateUtil.splitNotNumber(bxd.getDescription()));
            }
//            if(ToolUtil.isNotEmpty(bxd.getU_tenday())){
//                ekb.setDjbz("ten");
//            }
            logger.info("bxd.getPayeeInfo():" + bxd.getPayeeInfo());

            if (ToolUtil.isNotEmpty(bxd.getPayeeInfo())) {
                //ekb.setFkr(StringEscapeUtils.unescapeHtml4(bxd.getPayeeInfo().getName().replaceAll("\\s*", "")));
                ekb.setFkr(HtmlUtils.htmlUnescape(bxd.getPayeeInfo().getName().replace(" ", "")));
                String yhk = bxd.getPayeeInfo().getCardNo();
                ekb.setYhk(yhk);
                //通过银行卡号获取银行简称
                RestTemplate restTemplate = new RestTemplate();
                String url1 = "https://ccdcapi.alipay.com/validateAndCacheCardInfo.json?_input_charset=utf-8&cardNo=" + yhk + "&cardBinCheck=true";
                String content = restTemplate.getForObject(url1, String.class);
                JSONObject jsonObject = JSONObject.parseObject(content);

                String bank;
                if (ToolUtil.isNotEmpty(jsonObject.get("bank"))) {
                    //银行简称
                    bank = jsonObject.get("bank").toString();
                    //通过银行简称获取行号
                    String code = btyBxdaService.getBankCode(bank);
                    ekb.setHh(code);
                } else {
                    if (ToolUtil.isNotEmpty(yhk)) {
                        //BtyHh hh=hhService.getOne(new QueryWrapper<BtyHh>().eq("yhk",yhk));
                        List<BtyHh> list = hhService.list(new QueryWrapper<BtyHh>().eq("yhk", yhk));
                        if (list.size() > 0) {
                            ekb.setHh(list.get(0).getHh());
                        }
                    }
                }
                ekb.setBank(bxd.getPayeeInfo().getBank());
                ekb.setZhmc(bxd.getPayeeInfo().getBranch());
            }
            String bm = "";
            if (ToolUtil.isNotEmpty(bxd.getLoanDepartment())) {
                bm = bxd.getLoanDepartment().getName();
                if (bm.equals("半天妖潍坊高密金孚隆中心店")) {
                    bm = "潍坊高密金孚隆购物广场店";
                }
                if (bm.equals("半天妖福州万象九宜城店")) {
                    bm = "半天妖福建福州万象九宜城店";
                }
                if (bm.equals("半天妖青岛胶州利群购物广场店")) {
                    bm = "半天妖山东青岛胶州利群店";
                }
                if (bm.equals("上饶万达店")) {
                    bm = "上饶信州万达店";
                }
                if (bm.equals("半天妖江苏镇江吾悦店")) {
                    bm = "半天妖镇江吾悦店";
                }
                if (bm.equals("半天妖北京大兴宾馆店")) {
                    bm = "半天妖北京大兴店";
                }
                if (bm.equals("新乡新玛特")) {
                    bm = "新乡市大商新玛特店";
                }
                if (bm.equals("半天妖滕州人和店")) {
                    bm = "半天妖滕州人和广场店";
                }
                if (bm.equals("威海荣成九龙城店")) {
                    bm = "半天妖威海荣成市九龙城店";
                }
                if (bm.equals("杭州滨江宝龙城店")) {
                    bm = "半天妖杭州滨江宝龙城店";
                }
                ekb.setBm(bm);
            }
            if (ToolUtil.isNotEmpty(bxd.getExpenseDepartment())) {
                bm = bxd.getExpenseDepartment().getName();
                if (bm.equals("半天妖潍坊高密金孚隆中心店")) {
                    bm = "潍坊高密金孚隆购物广场店";
                }
                if (bm.equals("半天妖福州万象九宜城店")) {
                    bm = "半天妖福建福州万象九宜城店";
                }
                if (bm.equals("半天妖青岛胶州利群购物广场店")) {
                    bm = "半天妖山东青岛胶州利群店";
                }
                if (bm.equals("上饶万达店")) {
                    bm = "上饶信州万达店";
                }
                if (bm.equals("半天妖江苏镇江吾悦店")) {
                    bm = "半天妖镇江吾悦店";
                }
                if (bm.equals("半天妖北京大兴宾馆店")) {
                    bm = "半天妖北京大兴店";
                }
                if (bm.equals("新乡新玛特")) {
                    bm = "新乡市大商新玛特店";
                }
                if (bm.equals("半天妖滕州人和店")) {
                    bm = "半天妖滕州人和广场店";
                }
                if (bm.equals("威海荣成九龙城店")) {
                    bm = "半天妖威海荣成市九龙城店";
                }
                if (bm.equals("杭州滨江宝龙城店")) {
                    bm = "半天妖杭州滨江宝龙城店";
                }
                ekb.setBm(bm);
            }
            ekb.setSumAmount(new BigDecimal(bxd.getPayMoney().getAmount()));


            ekb.setYyr(DateUtil.getNowDate());
            ekb.setCjsj(new Date());
            //查询易快报单号是否已经存在，如果存在就更新，否则就保存数据
            BtyEkb btyEkb = ekbService.getOne(new QueryWrapper<BtyEkb>().eq("ekb_id", ekbId));
            if (ToolUtil.isNotEmpty(btyEkb)) {
                btyEkb.setBm(bm);
                if (ToolUtil.isNotEmpty(bxd.getPayeeInfo())) {
                    btyEkb.setBank(bxd.getPayeeInfo().getBank());
                    btyEkb.setZhmc(bxd.getPayeeInfo().getBranch());
                    btyEkb.setFkr(HtmlUtils.htmlUnescape(bxd.getPayeeInfo().getName().replace(" ", "")));
                    btyEkb.setYhk(bxd.getPayeeInfo().getCardNo());
                }
                btyEkb.setYyr(DateUtil.getNowDate());
                btyEkb.setCjsj(new Date());
                if (ToolUtil.isNotEmpty(bxd.getDescription())) {
                    btyEkb.setRemark(DateUtil.splitNotNumber(bxd.getDescription()));
                }
                List<BtyEkb> list8 = ekbService.list(new QueryWrapper<BtyEkb>().eq("ftid", btyEkb.getId()));
                if (list8.size() <= 0) {
                    btyEkb.setSumAmount(new BigDecimal(bxd.getPayMoney().getAmount()));
                }
                btyEkb.setBxr(bxd.getSubmitterId().getName());

                if (ToolUtil.isNotEmpty(btyEkb.getBms())) {
                    btyEkb.setBms(btyEkb.getBms());
                }
                if (ToolUtil.isNotEmpty(btyEkb.getFtbl())) {
                    btyEkb.setFtbl(btyEkb.getFtbl());
                }
                if (ToolUtil.isNotEmpty(btyEkb.getFtje())) {
                    btyEkb.setFtje(btyEkb.getFtje());
                }

                ekbService.updateById(btyEkb);
            } else {
                ekbService.save(ekb);
            }
            RestTemplate restTemplate = new RestTemplate();
            HttpHeaders headers = new HttpHeaders();
            MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
            headers.setContentType(type);
            JSONObject json = new JSONObject();
            json.put("appKey", "32de31e8-9a31-4cf9-a69b-74ddee365cf2");
            json.put("appSecurity", "149b3780-99bf-4431-976e-27d80896452f");
            headers.add("Accept", MediaType.APPLICATION_JSON.toString());
            HttpEntity<String> formEntity = new HttpEntity<String>(json.toString(), headers);
            String url = "https://dd2.ekuaibao.com/api/openapi/v1/auth/getAccessToken";
            String result = restTemplate.postForEntity(url, formEntity, String.class).getBody();
            JsonParser jp = new JsonParser();
            //将json字符串转化成json对象
            JsonObject jo = jp.parse(result).getAsJsonObject();
            //获取accessToken
            String accessToken = jo.get("value").getAsJsonObject().get("accessToken").getAsString();
            String url1 = "https://dd2.ekuaibao.com/api/openapi/v1/flowDetails?flowId=" + ekbId + "&accessToken=" + accessToken;
            Bill bill = restTemplate.getForEntity(url1, Bill.class).getBody();
            //费用分摊部门
            String bms = "";
            //费用分摊比例
            String ftbl = "";
            //费用分摊金额
            String ftjes = "";
            List<BtyEkb> ekbList=new ArrayList<>();

            //获取易快报报销单费用分摊的相关信息
            List<Bill.ValueBean.FormBean.Details> list = bill.getValue().getForm().getDetails();
            if(ToolUtil.isNotEmpty(list)&&list.size()>0) {
            for (Bill.ValueBean.FormBean.Details details : list) {
                if (ToolUtil.isNotEmpty(details.getFeeTypeForm().getApportions())) {
                    List<Bill.ValueBean.FormBean.Details.FeeTypeFormBean.ApportionsBean> apportionsBeanList = details.getFeeTypeForm().getApportions();
                    if (ToolUtil.isNotEmpty(apportionsBeanList) && apportionsBeanList.size() > 0) {
                        for (Bill.ValueBean.FormBean.Details.FeeTypeFormBean.ApportionsBean apportionsBean : apportionsBeanList) {
                            String apportionPercent = apportionsBean.getApportionForm().getApportionPercent();
                            ftbl = ftbl + apportionPercent + ",";
                            String ftje = apportionsBean.getApportionForm().getApportionMoney().getStandard();
                            ftjes = ftjes + ftje + ",";
                            String ftbmId = apportionsBean.getApportionForm().getExpenseDepartment();
                            //通过部门id获取部门名称
                            String url2 = "https://dd2.ekuaibao.com/api/openapi/v1/departments/$" + ftbmId + "?departmentBy=id&accessToken=" + accessToken;
                            String result2 = restTemplate.getForEntity(url2, String.class).getBody();
                            //将json字符串转化成json对象
                            JsonObject jo1 = jp.parse(result2).getAsJsonObject();
                            //获取部门名称
                            String bm1 = jo1.get("value").getAsJsonObject().get("name").getAsString();
                            if (bm1.equals("半天妖潍坊高密金孚隆中心店")) {
                                bm1 = "潍坊高密金孚隆购物广场店";
                            }
                            if (bm1.equals("半天妖福州万象九宜城店")) {
                                bm1 = "半天妖福建福州万象九宜城店";
                            }
                            if (bm1.equals("半天妖青岛胶州利群购物广场店")) {
                                bm1 = "半天妖山东青岛胶州利群店";
                            }
                            if (bm1.equals("上饶万达店")) {
                                bm1 = "上饶信州万达店";
                            }
                            if (bm1.equals("半天妖江苏镇江吾悦店")) {
                                bm1 = "半天妖镇江吾悦店";
                            }
                            if (bm1.equals("半天妖北京大兴宾馆店")) {
                                bm1 = "半天妖北京大兴店";
                            }
                            if (bm1.equals("新乡新玛特")) {
                                bm1 = "新乡市大商新玛特店";
                            }
                            if (bm1.equals("半天妖滕州人和店")) {
                                bm1 = "半天妖滕州人和广场店";
                            }
                            if (bm1.equals("威海荣成九龙城店")) {
                                bm1 = "半天妖威海荣成市九龙城店";
                            }
                            if (bm.equals("杭州滨江宝龙城店")) {
                                bm = "半天妖杭州滨江宝龙城店";
                            }
                            bms = bms + bm1 + ",";
                            //System.out.println("分摊部门："+bm1+"分摊比例:"+apportionPercent+  "分摊金额："+ftje);
                            BtyEkb ftEkb = new BtyEkb();
                            ftEkb.setId(UUIDUtils.getId());
                            BtyEkb ekb1 = ekbService.getOne(new QueryWrapper<BtyEkb>().eq("ekb_id", ekbId));
                            if (ToolUtil.isNotEmpty(ekb1)) {
                                ftEkb.setBxr(ekb1.getBxr());
                                ftEkb.setFkr(HtmlUtils.htmlUnescape(ekb1.getFkr().replace(" ", "")));
                                ftEkb.setCode(ekb1.getCode());
                                ftEkb.setFtid(ekb1.getId());
                                ftEkb.setBank(ekb1.getBank());
                                ftEkb.setYhk(ekb1.getYhk());
                                ftEkb.setZhmc(ekb1.getZhmc());
                                ftEkb.setHh(ekb1.getHh());
                                ftEkb.setRemark(ekb1.getRemark());
                                ftEkb.setTitle(ekb1.getTitle());
                                if (ToolUtil.isNotEmpty(ekb1.getDjbz())) {
                                    ftEkb.setDjbz(ekb1.getDjbz());
                                }
                            }
                            ftEkb.setSumAmount(new BigDecimal(ftje));
                            ftEkb.setBm(bm1);
                            ftEkb.setYyr(DateUtil.getNowDate());
                            ftEkb.setFtbz(0);
                            ekbList.add(ftEkb);
                            //ekbService.save(ftEkb);
                        }
                    }
                }
            }

                //每70条保存一次
                for(int i = 0; i < ekbList.size();){
                    int i2 = (i + 70);
                    i2 = i2 > ekbList.size() ? ekbList.size() : i2;
                    List<BtyEkb> sub = ekbList.subList(i, i2);
                    ekbService.insertEkb(sub);
                    i = i2;
                }
          }

            if(ftbl.length()>0){
                ftbl=ftbl.substring(0, ftbl.length()-1);
            }
            if(ftjes.length()>0){
                ftjes=ftjes.substring(0, ftjes.length()-1);
            }
            if(bms.length()>0){
                bms=bms.substring(0, bms.length()-1);
            }
            //更新费用承担部门，分摊比例，分摊费用到易快报表中
            BtyEkb ekb1 =ekbService.getOne(new QueryWrapper<BtyEkb>().eq("ekb_id",ekbId));
            List<BtyEkb>lists=new ArrayList<>();
            if(ToolUtil.isNotEmpty(ekb1)){
                lists=ekbService.list(new QueryWrapper<BtyEkb>().eq("ftid",ekb1.getId()));
            }
            if(ToolUtil.isNotEmpty(ekb1)&&lists.size()>0){
                if(ToolUtil.isNotEmpty(bms)){
                    ekb1.setBms(bms);
                }
                if(ToolUtil.isNotEmpty(ftbl)){
                    ekb1.setFtbl(ftbl);
                }
                if(ToolUtil.isNotEmpty(ftjes)){
                    ekb1.setFtje(ftjes);
                }
                ekb1.setFtbz(0);
                ekb1.setSumAmount(BigDecimal.ZERO);
                ekbService.updateById(ekb1);
            }

        } catch (Exception e) {
            logger.info("易快报异常："+e.getMessage());
            e.printStackTrace();
        }
        response.setStatus(204);
        return ResponseData.success();

    }


    /**
     * 易快报装修预付款报销单配置出站消息接口
     * @param bxd
     * @param response
     * @return
     */
    @ResponseBody
    @PostMapping("/zxBxd")
    public ResponseData zxBxd(@RequestBody Yfkbxd bxd, HttpServletResponse response) {
        try {
            logger.info("装修预付款报销单或核销单:"+bxd);
            BtyEkb ekb = new BtyEkb();
            ekb.setId(UUIDUtils.getId());
            ekb.setTitle(bxd.getTitle());
            ekb.setEkbId(bxd.getFlowId());
            String ekbId=bxd.getFlowId();
            ekb.setNodeId(bxd.getNodeId());
            ekb.setBxr(bxd.getSubmitterId().getName());
            ekb.setCode(bxd.getCode());
            //标志1 区分是易快报装修报销单
            ekb.setZx(1);
            if(ToolUtil.isNotEmpty(bxd.getDescription())){
                ekb.setRemark(DateUtil.splitNotNumber(bxd.getDescription()));
            }
//            if(ToolUtil.isNotEmpty(bxd.getU_tenday())){
//                ekb.setDjbz("ten");
//            }
            logger.info("bxd.getPayeeInfo():"+bxd.getPayeeInfo());

            if(ToolUtil.isNotEmpty(bxd.getPayeeInfo())){
                ekb.setFkr(HtmlUtils.htmlUnescape(bxd.getPayeeInfo().getName().replace(" ","")));
                String yhk = bxd.getPayeeInfo().getCardNo();
                ekb.setYhk(yhk);
                //通过银行卡号获取银行简称
                RestTemplate restTemplate = new RestTemplate();
                String url1 = "https://ccdcapi.alipay.com/validateAndCacheCardInfo.json?_input_charset=utf-8&cardNo=" + yhk + "&cardBinCheck=true";
                String content = restTemplate.getForObject(url1, String.class);
                JSONObject jsonObject = JSONObject.parseObject(content);

                String bank;
                if (ToolUtil.isNotEmpty(jsonObject.get("bank"))) {
                    //银行简称
                    bank = jsonObject.get("bank").toString();
                    //通过银行简称获取行号
                    String code = btyBxdaService.getBankCode(bank);
                    ekb.setHh(code);
                }else{
                    if(ToolUtil.isNotEmpty(yhk)){
                        //BtyHh hh=hhService.getOne(new QueryWrapper<BtyHh>().eq("yhk",yhk));
                        List<BtyHh> list=hhService.list(new QueryWrapper<BtyHh>().eq("yhk",yhk));
                        if(list.size()>0){
                            ekb.setHh(list.get(0).getHh());
                        }
                    }
                }
                ekb.setBank(bxd.getPayeeInfo().getBank());
                ekb.setZhmc(bxd.getPayeeInfo().getBranch());
            }
            String bm="";
            if(ToolUtil.isNotEmpty(bxd.getLoanDepartment())){
                bm=bxd.getLoanDepartment().getName();
                if(bm.equals("半天妖潍坊高密金孚隆中心店")){
                    bm="潍坊高密金孚隆购物广场店";
                }
                if(bm.equals("半天妖福州万象九宜城店")){
                    bm="半天妖福建福州万象九宜城店";
                }
                if(bm.equals("半天妖青岛胶州利群购物广场店")){
                    bm="半天妖山东青岛胶州利群店";
                }
                if(bm.equals("上饶万达店")){
                    bm="上饶信州万达店";
                }
                if(bm.equals("半天妖江苏镇江吾悦店")){
                    bm="半天妖镇江吾悦店";
                }
                if(bm.equals("半天妖北京大兴宾馆店")){
                    bm="半天妖北京大兴店";
                }
                if(bm.equals("新乡新玛特")){
                    bm="新乡市大商新玛特店";
                }
                if(bm.equals("半天妖滕州人和店")){
                    bm="半天妖滕州人和广场店";
                }
                if(bm.equals("威海荣成九龙城店")){
                    bm="半天妖威海荣成市九龙城店";
                }
                if(bm.equals("杭州滨江宝龙城店")){
                    bm="半天妖杭州滨江宝龙城店";
                }
                ekb.setBm(bm);
            }
            if(ToolUtil.isNotEmpty(bxd.getExpenseDepartment())){
                bm=bxd.getExpenseDepartment().getName();
                if(bm.equals("半天妖潍坊高密金孚隆中心店")){
                    bm="潍坊高密金孚隆购物广场店";
                }
                if(bm.equals("半天妖福州万象九宜城店")){
                    bm="半天妖福建福州万象九宜城店";
                }
                if(bm.equals("半天妖青岛胶州利群购物广场店")){
                    bm="半天妖山东青岛胶州利群店";
                }
                if(bm.equals("上饶万达店")){
                    bm="上饶信州万达店";
                }
                if(bm.equals("半天妖江苏镇江吾悦店")){
                    bm="半天妖镇江吾悦店";
                }
                if(bm.equals("半天妖北京大兴宾馆店")){
                    bm="半天妖北京大兴店";
                }
                if(bm.equals("新乡新玛特")){
                    bm="新乡市大商新玛特店";
                }
                if(bm.equals("半天妖滕州人和店")){
                    bm="半天妖滕州人和广场店";
                }
                if(bm.equals("威海荣成九龙城店")){
                    bm="半天妖威海荣成市九龙城店";
                }
                if(bm.equals("杭州滨江宝龙城店")){
                    bm="半天妖杭州滨江宝龙城店";
                }
                ekb.setBm(bm);
            }
            ekb.setSumAmount(new BigDecimal(bxd.getPayMoney().getAmount()));


            ekb.setYyr(DateUtil.getNowDate());
            ekb.setCjsj(new Date());
            //查询易快报单号是否已经存在，如果存在就更新，否则就保存数据
            BtyEkb btyEkb=ekbService.getOne(new QueryWrapper<BtyEkb>().eq("ekb_id",ekbId));
            if(ToolUtil.isNotEmpty(btyEkb)){
                btyEkb.setBm(bm);
                btyEkb.setBank(bxd.getPayeeInfo().getBank());
                btyEkb.setZhmc(bxd.getPayeeInfo().getBranch());
                btyEkb.setYyr(DateUtil.getNowDate());
                btyEkb.setCjsj(new Date());
                btyEkb.setZx(1);
                if(ToolUtil.isNotEmpty(bxd.getDescription())){
                    btyEkb.setRemark(DateUtil.splitNotNumber(bxd.getDescription()));
                }
                List<BtyEkb>list8=ekbService.list(new QueryWrapper<BtyEkb>().eq("ftid",btyEkb.getId()));
                if(list8.size()<=0){
                    btyEkb.setSumAmount(new BigDecimal(bxd.getPayMoney().getAmount()));
                }
                btyEkb.setBxr(bxd.getSubmitterId().getName());
                btyEkb.setFkr(HtmlUtils.htmlUnescape(bxd.getPayeeInfo().getName().replace(" ","")));
                if(ToolUtil.isNotEmpty(btyEkb.getBms())){
                    btyEkb.setBms(btyEkb.getBms());
                }
                if(ToolUtil.isNotEmpty(btyEkb.getFtbl())){
                    btyEkb.setFtbl(btyEkb.getFtbl());
                }
                if(ToolUtil.isNotEmpty(btyEkb.getFtje())){
                    btyEkb.setFtje(btyEkb.getFtje());
                }
                btyEkb.setYhk(bxd.getPayeeInfo().getCardNo());
                ekbService.updateById(btyEkb);
            }else {
                ekbService.save(ekb);
            }
            RestTemplate restTemplate=new RestTemplate();
            HttpHeaders headers = new HttpHeaders();
            MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
            headers.setContentType(type);
            JSONObject json = new JSONObject();
            json.put("appKey", "32de31e8-9a31-4cf9-a69b-74ddee365cf2");
            json.put("appSecurity", "149b3780-99bf-4431-976e-27d80896452f");
            headers.add("Accept", MediaType.APPLICATION_JSON.toString());
            HttpEntity<String> formEntity = new HttpEntity<String>(json.toString(), headers);
            String url = "https://dd2.ekuaibao.com/api/openapi/v1/auth/getAccessToken";
            String result = restTemplate.postForEntity(url, formEntity, String.class).getBody();
            JsonParser jp = new JsonParser();
            //将json字符串转化成json对象
            JsonObject jo = jp.parse(result).getAsJsonObject();
            //获取accessToken
            String accessToken = jo.get("value").getAsJsonObject().get("accessToken").getAsString();
            String url1 = "https://dd2.ekuaibao.com/api/openapi/v1/flowDetails?flowId="+ekbId+"&accessToken=" + accessToken;
            Bill bill = restTemplate.getForEntity(url1,Bill.class).getBody();
            //费用分摊部门
            String bms = "";
            //费用分摊比例
            String ftbl="";
            //费用分摊金额
            String ftjes="";
            //获取易快报报销单费用分摊的相关信息
            List<Bill.ValueBean.FormBean.Details> list=bill.getValue().getForm().getDetails();
            for (Bill.ValueBean.FormBean.Details details : list) {
                if(ToolUtil.isNotEmpty(details.getFeeTypeForm().getApportions())) {
                    List<Bill.ValueBean.FormBean.Details.FeeTypeFormBean.ApportionsBean> apportionsBeanList = details.getFeeTypeForm().getApportions();
                    for (Bill.ValueBean.FormBean.Details.FeeTypeFormBean.ApportionsBean apportionsBean : apportionsBeanList) {
                        String  apportionPercent=apportionsBean.getApportionForm().getApportionPercent();
                        ftbl=ftbl+apportionPercent+",";
                        String ftje=apportionsBean.getApportionForm().getApportionMoney().getStandard();
                        ftjes=ftjes+ftje+",";
                        String ftbmId=apportionsBean.getApportionForm().getExpenseDepartment();
                        //通过部门id获取部门名称
                        String url2 = "https://dd2.ekuaibao.com/api/openapi/v1/departments/$"+ftbmId+"?departmentBy=id&accessToken=" + accessToken;
                        String result2 = restTemplate.getForEntity(url2,String.class).getBody();
                        //将json字符串转化成json对象
                        JsonObject jo1 = jp.parse(result2).getAsJsonObject();
                        //获取部门名称
                        String bm1 = jo1.get("value").getAsJsonObject().get("name").getAsString();
                        if(bm1.equals("半天妖潍坊高密金孚隆中心店")){
                            bm1="潍坊高密金孚隆购物广场店";
                        }
                        if(bm1.equals("半天妖福州万象九宜城店")){
                            bm1="半天妖福建福州万象九宜城店";
                        }
                        if(bm1.equals("半天妖青岛胶州利群购物广场店")){
                            bm1="半天妖山东青岛胶州利群店";
                        }
                        if(bm1.equals("上饶万达店")){
                            bm1="上饶信州万达店";
                        }
                        if(bm1.equals("半天妖江苏镇江吾悦店")){
                            bm1="半天妖镇江吾悦店";
                        }
                        if(bm1.equals("半天妖北京大兴宾馆店")){
                            bm1="半天妖北京大兴店";
                        }
                        if(bm1.equals("新乡新玛特")){
                            bm1="新乡市大商新玛特店";
                        }
                        if(bm1.equals("半天妖滕州人和店")){
                            bm1="半天妖滕州人和广场店";
                        }
                        if(bm1.equals("威海荣成九龙城店")){
                            bm1="半天妖威海荣成市九龙城店";
                        }
                        if(bm.equals("杭州滨江宝龙城店")){
                            bm="半天妖杭州滨江宝龙城店";
                        }
                        bms=bms+bm1+",";
                        //System.out.println("分摊部门："+bm1+"分摊比例:"+apportionPercent+  "分摊金额："+ftje);
                        BtyEkb ftEkb=new BtyEkb();
                        ftEkb.setId(UUIDUtils.getId());
                        BtyEkb ekb1=ekbService.getOne(new QueryWrapper<BtyEkb>().eq("ekb_id",ekbId));
                        if(ToolUtil.isNotEmpty(ekb1)){
                            ftEkb.setBxr(ekb1.getBxr());
                            ftEkb.setFkr(HtmlUtils.htmlUnescape(ekb1.getFkr().replace(" ","")));
                            ftEkb.setCode(ekb1.getCode());
                            ftEkb.setFtid(ekb1.getId());
                            ftEkb.setBank(ekb1.getBank());
                            ftEkb.setYhk(ekb1.getYhk());
                            ftEkb.setZhmc(ekb1.getZhmc());
                            ftEkb.setHh(ekb1.getHh());
                            ftEkb.setRemark(ekb1.getRemark());
                            ftEkb.setTitle(ekb1.getTitle());
                            ftEkb.setZx(1);
                            if(ToolUtil.isNotEmpty(ekb1.getDjbz())){
                                ftEkb.setDjbz(ekb1.getDjbz());
                            }
                        }
                        ftEkb.setSumAmount(new BigDecimal(ftje));
                        ftEkb.setBm(bm1);
                        ftEkb.setYyr(DateUtil.getNowDate());
                        ftEkb.setFtbz(0);
                        ekbService.save(ftEkb);
                    }
                }
            }
            if(ftbl.length()>0){
                ftbl=ftbl.substring(0, ftbl.length()-1);
            }
            if(ftjes.length()>0){
                ftjes=ftjes.substring(0, ftjes.length()-1);
            }
            if(bms.length()>0){
                bms=bms.substring(0, bms.length()-1);
            }
            //更新费用承担部门，分摊比例，分摊费用到易快报表中
            BtyEkb ekb1 =ekbService.getOne(new QueryWrapper<BtyEkb>().eq("ekb_id",ekbId));
            List<BtyEkb>lists=new ArrayList<>();
            if(ToolUtil.isNotEmpty(ekb1)){
                lists=ekbService.list(new QueryWrapper<BtyEkb>().eq("ftid",ekb1.getId()));
            }
            if(ToolUtil.isNotEmpty(ekb1)&&lists.size()>0){
                if(ToolUtil.isNotEmpty(bms)){
                    ekb1.setBms(bms);
                }
                if(ToolUtil.isNotEmpty(ftbl)){
                    ekb1.setFtbl(ftbl);
                }
                if(ToolUtil.isNotEmpty(ftjes)){
                    ekb1.setFtje(ftjes);
                }
                ekb1.setFtbz(0);
                ekb1.setSumAmount(BigDecimal.ZERO);
                ekbService.updateById(ekb1);
            }

        } catch (Exception e) {
            logger.info("易快报异常："+e.getMessage());
            e.printStackTrace();
        }
        response.setStatus(204);
        return ResponseData.success();

    }


    /**
     * 易快报申请单配置出站消息接口
     * @param
     * @param response
     * @return
     */
    @ResponseBody
    @PostMapping("/ekbSqd")///ekbYfkbxd
    public ResponseData ekbSqd(@RequestBody Sqd bxd, HttpServletResponse response) {
        try {
            System.out.println("申请单："+bxd);
            logger.info("申请单:"+bxd);
            BtyEkb ekb = new BtyEkb();
            ekb.setId(UUIDUtils.getId());
            ekb.setTitle(bxd.getTitle());
            ekb.setEkbId(bxd.getFlowId());
            String ekbId=bxd.getFlowId();
            ekb.setNodeId(bxd.getNodeId());
            ekb.setBxr(bxd.getSubmitterId().getName());
            ekb.setFkr(HtmlUtils.htmlUnescape(bxd.getSubmitterId().getName().replace(" ","")));
            ekb.setCode(bxd.getCode());
            String bm=bxd.getExpenseDepartment().getName();
            if(bm.equals("半天妖潍坊高密金孚隆中心店")){
                bm="潍坊高密金孚隆购物广场店";
            }
            if(bm.equals("半天妖福州万象九宜城店")){
                bm="半天妖福建福州万象九宜城店";
            }
            if(bm.equals("半天妖青岛胶州利群购物广场店")){
                bm="半天妖山东青岛胶州利群店";
            }
            if(bm.equals("上饶万达店")){
                bm="上饶信州万达店";
            }
            if(bm.equals("半天妖江苏镇江吾悦店")){
                bm="半天妖镇江吾悦店";
            }
            if(bm.equals("半天妖北京大兴宾馆店")){
                bm="半天妖北京大兴店";
            }
            if(bm.equals("新乡新玛特")){
                bm="新乡市大商新玛特店";
            }
            if(bm.equals("半天妖滕州人和店")){
                bm="半天妖滕州人和广场店";
            }
            if(bm.equals("威海荣成九龙城店")){
                bm="半天妖威海荣成市九龙城店";
            }
            if(bm.equals("杭州滨江宝龙城店")){
                bm="半天妖杭州滨江宝龙城店";
            }
            ekb.setBm(bm);
            if(ToolUtil.isNotEmpty(bxd.getDescription())){
                ekb.setRemark(DateUtil.splitNotNumber(bxd.getDescription()));
            }
            ekb.setSumAmount(new BigDecimal(bxd.getRequisitionMoney().getAmount()));
            ekb.setYyr(DateUtil.getNowDate());
            ekb.setCjsj(new Date());
            //查询易快报单号是否已经存在，如果存在就更新，否则就保存数据
            BtyEkb btyEkb=ekbService.getOne(new QueryWrapper<BtyEkb>().eq("ekb_id",ekbId));

            if(ToolUtil.isNotEmpty(btyEkb)){
                btyEkb.setBm(bm);
                btyEkb.setYyr(DateUtil.getNowDate());
                btyEkb.setCjsj(new Date());
                if(ToolUtil.isNotEmpty(bxd.getDescription())){
                    btyEkb.setRemark(DateUtil.splitNotNumber(bxd.getDescription()));
                }
                List<BtyEkb>list8=ekbService.list(new QueryWrapper<BtyEkb>().eq("ftid",btyEkb.getId()));
                if(list8.size()<=0) {
                    btyEkb.setSumAmount(new BigDecimal(bxd.getRequisitionMoney().getAmount()));
                }
                btyEkb.setBxr(bxd.getSubmitterId().getName());
                btyEkb.setFkr(HtmlUtils.htmlUnescape(bxd.getSubmitterId().getName().replace(" ","")));

                if(ToolUtil.isNotEmpty(btyEkb.getBms())){
                    btyEkb.setBms(btyEkb.getBms());
                }
                if(ToolUtil.isNotEmpty(btyEkb.getFtbl())){
                    btyEkb.setFtbl(btyEkb.getFtbl());
                }
                if(ToolUtil.isNotEmpty(btyEkb.getFtje())){
                    btyEkb.setFtje(btyEkb.getFtje());
                }
                ekbService.updateById(btyEkb);
            }else {
                ekbService.save(ekb);
            }
            RestTemplate restTemplate=new RestTemplate();
            HttpHeaders headers = new HttpHeaders();
            MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
            headers.setContentType(type);
            JSONObject json = new JSONObject();
            json.put("appKey", "32de31e8-9a31-4cf9-a69b-74ddee365cf2");
            json.put("appSecurity", "149b3780-99bf-4431-976e-27d80896452f");
            headers.add("Accept", MediaType.APPLICATION_JSON.toString());
            HttpEntity<String> formEntity = new HttpEntity<String>(json.toString(), headers);
            String url = "https://dd2.ekuaibao.com/api/openapi/v1/auth/getAccessToken";
            String result = restTemplate.postForEntity(url, formEntity, String.class).getBody();
            JsonParser jp = new JsonParser();
            //将json字符串转化成json对象
            JsonObject jo = jp.parse(result).getAsJsonObject();
            //获取accessToken
            String accessToken = jo.get("value").getAsJsonObject().get("accessToken").getAsString();
            String url1 = "https://dd2.ekuaibao.com/api/openapi/v1/flowDetails?flowId="+ekbId+"&accessToken=" + accessToken;
            Bill bill = restTemplate.getForEntity(url1,Bill.class).getBody();
            //费用分摊部门
            String bms = "";
            //费用分摊比例
            String ftbl="";
            //费用分摊金额
            String ftjes="";
            //获取易快报报销单费用分摊的相关信息
            List<Bill.ValueBean.FormBean.Details> list=bill.getValue().getForm().getDetails();
            for (Bill.ValueBean.FormBean.Details details : list) {
                if(ToolUtil.isNotEmpty(details.getFeeTypeForm().getApportions())) {
                    List<Bill.ValueBean.FormBean.Details.FeeTypeFormBean.ApportionsBean> apportionsBeanList = details.getFeeTypeForm().getApportions();
                    for (Bill.ValueBean.FormBean.Details.FeeTypeFormBean.ApportionsBean apportionsBean : apportionsBeanList) {
                        String  apportionPercent=apportionsBean.getApportionForm().getApportionPercent();
                        ftbl=ftbl+apportionPercent+",";
                        String ftje=apportionsBean.getApportionForm().getApportionMoney().getStandard();
                        ftjes=ftjes+ftje+",";
                        String ftbmId=apportionsBean.getApportionForm().getExpenseDepartment();
                        //通过部门id获取部门名称
                        String url2 = "https://dd2.ekuaibao.com/api/openapi/v1/departments/$"+ftbmId+"?departmentBy=id&accessToken=" + accessToken;
                        String result2 = restTemplate.getForEntity(url2,String.class).getBody();
                        //将json字符串转化成json对象
                        JsonObject jo1 = jp.parse(result2).getAsJsonObject();
                        //获取部门名称
                        String bm1 = jo1.get("value").getAsJsonObject().get("name").getAsString();
                        if(bm1.equals("半天妖潍坊高密金孚隆中心店")){
                            bm1="潍坊高密金孚隆购物广场店";
                        }
                        if(bm1.equals("半天妖福州万象九宜城店")){
                            bm1="半天妖福建福州万象九宜城店";
                        }
                        if(bm1.equals("半天妖青岛胶州利群购物广场店")){
                            bm1="半天妖山东青岛胶州利群店";
                        }
                        if(bm1.equals("上饶万达店")){
                            bm1="上饶信州万达店";
                        }
                        if(bm1.equals("半天妖江苏镇江吾悦店")){
                            bm1="半天妖镇江吾悦店";
                        }
                        if(bm1.equals("半天妖北京大兴宾馆店")){
                            bm1="半天妖北京大兴店";
                        }
                        if(bm1.equals("新乡新玛特")){
                            bm1="新乡市大商新玛特店";
                        }
                        if(bm1.equals("半天妖滕州人和店")){
                            bm1="半天妖滕州人和广场店";
                        }
                        if(bm1.equals("威海荣成九龙城店")){
                            bm1="半天妖威海荣成市九龙城店";
                        }
                        if(bm1.equals("杭州滨江宝龙城店")){
                            bm1="半天妖杭州滨江宝龙城店";
                        }
                        bms=bms+bm1+",";
                        //System.out.println("分摊部门："+bm1+"分摊比例:"+apportionPercent+  "分摊金额："+ftje);
                        BtyEkb ftEkb=new BtyEkb();
                        ftEkb.setId(UUIDUtils.getId());
                        BtyEkb ekb1=ekbService.getOne(new QueryWrapper<BtyEkb>().eq("ekb_id",ekbId));
                        if(ToolUtil.isNotEmpty(ekb1)){
                            ftEkb.setBxr(ekb1.getBxr());
                            ftEkb.setFkr(HtmlUtils.htmlUnescape(ekb1.getFkr().replace(" ","")));
                            ftEkb.setCode(ekb1.getCode());
                            ftEkb.setFtid(ekb1.getId());
                            ftEkb.setBank(ekb1.getBank());
                            ftEkb.setYhk(ekb1.getYhk());
                            ftEkb.setZhmc(ekb1.getZhmc());
                            ftEkb.setHh(ekb1.getHh());
                            ftEkb.setRemark(ekb1.getRemark());
                            ftEkb.setTitle(ekb1.getTitle());
                            if(ToolUtil.isNotEmpty(ekb1.getDjbz())){
                                ftEkb.setDjbz(ekb1.getDjbz());
                            }
                        }
                        ftEkb.setSumAmount(new BigDecimal(ftje));
                        ftEkb.setBm(bm1);
                        ftEkb.setYyr(DateUtil.getNowDate());
                        ftEkb.setFtbz(0);
                        ekbService.save(ftEkb);
                    }
                }
            }
            if(ftbl.length()>0){
                ftbl=ftbl.substring(0, ftbl.length()-1);
            }
            if(ftjes.length()>0){
                ftjes=ftjes.substring(0, ftjes.length()-1);
            }
            if(bms.length()>0){
                bms=bms.substring(0, bms.length()-1);
            }
            //更新费用承担部门，分摊比例，分摊费用到易快报表中
            BtyEkb ekb1 =ekbService.getOne(new QueryWrapper<BtyEkb>().eq("ekb_id",ekbId));
            List<BtyEkb>lists=new ArrayList<>();
            if(ToolUtil.isNotEmpty(ekb1)){
                lists=ekbService.list(new QueryWrapper<BtyEkb>().eq("ftid",ekb1.getId()));
            }
            if(ToolUtil.isNotEmpty(ekb1)&&lists.size()>0){
                if(ToolUtil.isNotEmpty(bms)){
                    ekb1.setBms(bms);
                }
                if(ToolUtil.isNotEmpty(ftbl)){
                    ekb1.setFtbl(ftbl);
                }
                if(ToolUtil.isNotEmpty(ftjes)){
                    ekb1.setFtje(ftjes);
                }
                ekb1.setFtbz(0);
                ekb1.setSumAmount(BigDecimal.ZERO);
                ekbService.updateById(ekb1);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        response.setStatus(204);
        return ResponseData.success();

    }
    /**
     * 版本更新列表
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/versionList")
    public ResponseData versionList(){
        List<Notice>list=noticeService.list(new QueryWrapper<Notice>().orderByDesc("create_time"));
        if(list.size()>0){
            return ResponseData.success(list.get(0));
        }
        return ResponseData.success();
    }

    @ResponseBody
    @RequestMapping("/hyksj")
    public ResponseData hyksj(@RequestBody Yhksj yhksj,HttpServletRequest request) {
        String url=yhksj.getRpData().getUrl();
        try {
            System.out.println("url:"+url);
        } catch (RestClientException e) {
            e.printStackTrace();
        }
        return ResponseData.success(url);

    }

    /**
     * tpos交易列表
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/tposList")
    public String tposList() throws JsonProcessingException {
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");//设置日期格式
        String orderNo = df.format(new Date());
        SimpleDateFormat df1 = new SimpleDateFormat("HH:mm");
        //String number = DateUtil.getYesterDayTime();
        String jyrq=DateUtil.getNowDate();
        String time=df1.format(new Date());
        String money="6.66";
        JSONObject dataJson = new JSONObject();
        dataJson.put("account_id", "");
        dataJson.put("account_type", "");
        Map rmDetail = new HashMap();
        rmDetail.put("account_id", "");
        rmDetail.put("sell_storeid", "");
        rmDetail.put("sell_posid", "");
        rmDetail.put("tenants_sell_posid", "SERVER");
        rmDetail.put("total_amt", money);
        rmDetail.put("tenants_sell_no", orderNo);
        rmDetail.put("tenants_sell_day", jyrq);
        rmDetail.put("tenants_sell_time", time);
        rmDetail.put("sell_transtype", "X1");

        List<Map<String, Object>> rmDetailList = new ArrayList<>();
        rmDetailList.add(rmDetail);

        Map sellDetail = new HashMap();
        sellDetail.put("sell_id","11111");
        sellDetail.put("sell_name","熙地港");
        sellDetail.put("sell_qty","1");
        sellDetail.put("sell_price",money);
        sellDetail.put("sell_discount","");
        sellDetail.put("sell_amt",money);
        List<Map<String, Object>> sellDetailList = new ArrayList<>();
        sellDetailList.add(sellDetail);
        rmDetail.put("sell_detail",sellDetailList);

        Map map = new HashMap();
        map.put("sell_tender", "01");
        map.put("tender_price", money);
        List<Map<String, Object>> payList = new ArrayList<>();
        payList.add(map);
        dataJson.put("rm_detail",rmDetailList);
        dataJson.put("tender_detail", payList);
        ObjectMapper mapper = new ObjectMapper();
        System.out.println("json:"+mapper.writerWithDefaultPrettyPrinter().writeValueAsString(dataJson));
        return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(dataJson);
    }


}
